<?php

/**
 * 腾讯云回调
 *
 * Created by PhpStorm.
 * User: evan
 * Date: 2017/8/15
 * Time: 下午12:01
 */
class Callback extends MY_Api_Controller
{
    public function index()
    {
        $content = file_get_contents("php://input");
        //$this->log('All:'.$content);
        /*主播推流
        $content = '
        {
            "app": "9342.livepush.myqcloud.com",
            "appid": 1253714904,
            "appname": "live",
            "channel_id": "9342_testing_547_1",
            "errcode": 0,
            "errmsg": "",
            "event_time": 1503639736,
            "event_type": 1,
            "idc_id": 32,
            "node": "116.31.69.106",
            "sequence": "14533462390633018083",
            "set_id": 2,
            "sign": "736f9e37fd661c52c86548d995d0e31f",
            "stream_id": "9342_testing_547_1",
            "stream_param": "bizid=9342&txSecret=d9ed7458aaca86daa202b8f186af1704&txTime=59A0497F",
            "t": 1503640337,
            "user_ip": "218.76.1.133"
        }
        ';
        /*/
        /*副主播推流
        $content = '
        {
            "app": "9342.livepush.myqcloud.com",
            "appid": 1253714904,
            "appname": "live",
            "channel_id": "9342_development_547_2",
            "errcode": 0,
            "errmsg": "",
            "event_time": 1503641747,
            "event_type": 1,
            "idc_id": 32,
            "node": "116.31.69.151",
            "sequence": "443714947984448375",
            "set_id": 2,
            "sign": "9f2d04829f89813042dce176c776f1fb",
            "stream_id": "9342_development_547_2",
            "stream_param": "bizid=9342&txSecret=c27e5bf335c96a7f6732c2a95b8c990f&txTime=59A0497F",
            "t": 1503642347,
            "user_ip": "218.76.1.133"
        }
        ';
        //*/
        /*生成视频后回调
        $content = '
        {
            "appid": 1253714904,
            "channel_id": "9342_production_1565_2",
            "duration": 6,
            "end_time": 1508407797,
            "event_type": 100,
            "file_format": "mp4",
            "file_id": "9031868223385394470",
            "file_size": 1046715,
            "media_start_time": 3839,
            "record_file_id": "9031868223385394470",
            "sign": "06a9a6229eba9b16c44f619490ceb4fc",
            "start_time": 1508407792,
            "stream_id": "9342_production_1565_2",
            "stream_param": "bizid=9342&txSecret=347b70f91803d7010b60dded9a980a0d&txTime=59E8E6F4&record=mp4",
            "t": 1508408399,
            "task_id": "511374240",
            "video_id": "210003744_9e19fb29b38a4517994e010fd28b1894",
            "video_url": "http://1253714904.vod2.myqcloud.com/34cf9c43vodgzp1253714904/1bbdb6ca9031868223385394470/f0.mp4"
        }
        ';
        //*/

        if (empty($content))
        {
            $this->log('callback! 回调内容为空!');
            return false;
        }

        $item = json_decode($content, true);


        //验证事件类型
        if (!isset($item['event_type']))
        {
            $this->log('callback! 回调数据错误!缺少event_type');
            return false;
        }


        //验证回调正确性
        if (!isset($item['sign']))
        {
            $this->log('callback! 回调数据错误!缺少sign');
            return false;
        }


        $sign = md5(QCLOUD_API_KEY.$item['t']);
        if ($sign != $item['sign'])
        {
            $this->log('callback! 回调数据错误!sign错误');
            return false;
        }


        //处理测试环境的视频录制回调入库
        if ('production' == ENVIRONMENT && false !== strpos($item['stream_id'], 'testing'))
        {
            $t = vPost('http://api-test-old.shikee.tv/direct_seeding/Callback/index', $content);
            echo json_encode(array('code' => 0));
            return false;
        }


        //消息类型的通知：0 — 断流； 1 — 推流；100 — 新的录制文件已生成；200 — 新的截图文件已生成
        switch ($item['event_type'])
        {
            case '0'://断流；
                $this->process_0($item);
                break;
            case '1'://推流
                $this->process_1($item);
                break;
            case '100'://新的录制文件已生成
                $this->process_100($item);
                break;
            case '200'://新的截图文件已生成
                $this->process_200($item);
                break;
            default:
                $this->log('callback! 未知的事件类型!');
                break;
        }


        echo json_encode(array('code' => 0));
    }


    /**
     * 断流
     *
     * @param array $item
     * @return bool
     */
    public function process_0(array $item)
    {
        $this->log('0:'.json_encode($item));


        //副主播开始断流，即取消混流
        $tmp = explode('_', $item['stream_id']);
        $ds_id = isset($tmp[2]) ? $tmp[2] : 0;
        $is_be = isset($tmp[3]) ? $tmp[3] : 0;


        if (!$ds_id || !$is_be)
        {
            $this->log('callback! 回调数据错误!直播ID与主副播参数错误');
            return false;
        }


        if (2 != $is_be)
        {
            return false;
        }


        $this->load->service('direct_seeding/service_direct_seeding_mixed_flow');
        $data = $this->service_direct_seeding_mixed_flow->index($ds_id, DIRECT_SEEDING_MIXED_FLOW_TYPE_CLOSED);
        $this->log('callback close api!'.print_r($data, true));
    }


    /**
     * 推流
     *
     * @param array $item
     * @return bool
     */
    private function process_1(array $item)
    {
        $this->log('1:'.json_encode($item));


        //副主播开始推流，即进行混流
        $tmp = explode('_', $item['stream_id']);
        $ds_id = isset($tmp[2]) ? $tmp[2] : 0;
        $is_be = isset($tmp[3]) ? $tmp[3] : 0;


        if (!$ds_id || !$is_be)
        {
            $this->log('callback! 回调数据错误!直播ID与主副播参数错误');
            return false;
        }


        /*
        if (2 != $is_be)
        {
            return false;
        }
        //*/


        $this->load->service('direct_seeding/service_direct_seeding_mixed_flow');
        $data = $this->service_direct_seeding_mixed_flow->index($ds_id, DIRECT_SEEDING_MIXED_FLOW_TYPE_ENABLE);
        $this->log('callback enable api!'.print_r($data, true));
    }


    /**
     * 新的录制文件已生成
     *
     * @param array $item
     * @return bool
     */
    private function process_100(array $item)
    {
        $this->log('100:'.json_encode($item));


        $tmp = explode('_', $item['stream_id']);
        $ds_id = (int)isset($tmp[2]) ? $tmp[2] : 0;
        $is_be = (int)isset($tmp[3]) ? $tmp[3] : 0;

        if (!$ds_id)
        {
            $this->log('callback! 回调数据错误!直播ID与主副播参数错误');
            return false;
        }


        if (!array_key_exists($is_be, config_item('direct_seeding_playback_video_types')))
        {
            $this->log('callback! 视频流类型错误!'.$is_be);
            return false;
        }


        $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
        $ds_item = $this->ds->getById($ds_id);
        if (empty($ds_item))
        {
            $this->log('callback! 直播不存在!');
            return false;
        }


        $this->load->model('direct_seeding/Model_direct_seeding_video_link', 'dsvl');
        $count = $this->dsvl->count(array('ds_id' => $ds_id));


        $duration = $item['end_time'] - $item['start_time'];
        $rs = $this->dsvl->record($ds_id, $item['video_url'], $duration, $item['start_time'], json_encode($item), $is_be, ($count + 1), $item['stream_id']);

        $this->log(print_r($rs, true));
        $this->log('100: 录制文件记录'.(200 == $rs['status'] ? '成功' : '失败'));
    }


    /**
     * 新的截图文件已生成
     *
     * @param array $item
     */
    private function process_200(array $item)
    {
        $this->log('200:'.json_encode($item));
    }
}